<?php
/**
 * Overview page of all translation for this webform.
 */
function webform_translation_page($node, $page_number=1) {
  $lang = _get_webform_translation(WEBFORM_DEFAULT_LANGUAGE);
  
  // Set default translate language in session
  if (!isset($_SESSION['language'])) {
    $_SESSION['language'] = array('lid'=>2, 'lcode'=>'de', 'name'=>'German');
  }
  
  // Set the request language in session
  if (isset($_REQUEST['language']) && isset($lang['lid'][$_REQUEST['language']])) {
	$_SESSION['language'] = array('lid'=>$lang['lid'][$_REQUEST['language']], 'lcode'=>$_REQUEST['language'], 'name'=>$lang['name'][$_REQUEST['language']]);
  }
  
  $output = drupal_get_form('webform_translation_form', $node);

  return array(
      '#theme' => 'webform_translation_page',
      '#node' => $node,
      '#form' => $output,
  );
}

/**
 * Theme the output of the main translation page.
 *
 * This theming provides a way to toggle between the editing modes if Form
 * Builder module is available.
 */
function theme_webform_translation_page($variables) {
  $node = $variables['node'];
  $form = $variables['form'];

  return drupal_render($form);
}

/**
 * The table-based listing of all translation for this webform.
 */
function webform_translation_form($form, $form_state, $node) {
  global $base_url;
  
  $lang = _get_webform_translation(WEBFORM_DEFAULT_LANGUAGE);
  $lang = $lang['name'];
  
  $form = array(
      '#tree' => TRUE,
      '#node' => $node,
      'components' => array(),
  );

  $form['nid'] = array(
      '#type' => 'value',
      '#value' => $node->nid,
  );

  //translation input add robert
  $lid   = $_SESSION['language']['lid'];
  $lcode = $_SESSION['language']['lcode'];
  $translations = _get_webform_component_translation($node->nid, $lid);
  //end
  
  //translation select add
  $form['components']['translation_select'] = array(
    '#type' => 'select',
    '#title' => t('Translation'),
    '#options' => $lang,
    '#default_value' => $lcode,
    '#required' => true,
    '#attributes' => array('onchange' => 'window.location.href=\'?language=\'+this.options[this.selectedIndex].value'),
    '#weight' => -10000,
  );
  
  

  $options = array();
  foreach ($node->webform['components'] as $cid => $component) {
    $options[$cid] = check_plain($component['name']);
    //$form['components'][$cid]['cid'] = array(
    //    '#type' => 'hidden',
    //    '#default_value' => $component['cid'],
    //);
    
    //translation input add
    $form['components'][$cid]['translation'] = array(
        '#type' => empty($lcode) ? 'hidden' : 'textfield',
        '#size' => 14,
        '#default_value' => isset($translations[$cid]->name) ? $translations[$cid]->name : '',
        '#attributes' => array('style' => 'width:300px'),
        '#maxlength' => 255*2,
    );
    //end
  }

  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save'),
      '#executes_submit_callback'=>'webform_translation_form_submit',
      '#weight' => -45,
  );
  //print_r($node->webform['components']);die;
  //end
  
  $redirect = $base_url.'/'.request_path().'?language='.$lcode ;
  $form['#redirect'] = $redirect;
  return $form;
}

/**
 * Theme the node translation form. Use a table to organize the translation.
 *
 * @param $form
 *   The form array.
 * @return
 *   Formatted HTML form, ready for display.
 */
function theme_webform_translation_form($variables) {
  $form = $variables['form'];
  $form['components']['#attached']['library'][] = array('webform', 'admin');

  $node = $form['#node'];
  $header = array(t('Label'), t('Type'), t('Translation'), t('Operations'));
  $rows = array();


  $form['add']['name']['#attributes']['rel'] = t('New component name');
  $form['add']['translation']['#attributes']['class'] = array('webform-weight');
  
  
  $row_data = array(
      drupal_render($form['add']['name']),
	  drupal_render($form['add']['type']),
      drupal_render($form['add']['translation']),
      drupal_render($form['add']['edit']),
  );
  
  $add_form = array('data' => $row_data, 'class' => array('draggable', 'webform-add-form'));
  $form_rendered = FALSE;
  

  if (!empty($node->webform['components'])) {
    $component_tree = array();
    $page_count = 1;
    _webform_components_tree_build($node->webform['components'], $component_tree, 0, $page_count);
    
    
    $component_tree = _webform_components_tree_sort($component_tree);
    // Build the table rows.
    
    function _webform_components_form_rows($node, $cid, $component, $level, &$form, &$rows, &$add_form) {
      // Create presentable values.


      // Build indentation for this row.
      $indents = '';
      for ($n = 1; $n <= $level; $n++) {
        $indents .= '<div class="indentation">&nbsp;</div>';
      }

      // Add each component to a table row.
      //print_r($form['components'][$cid]['translation']);die;
      $row_data = array(
          $indents . filter_xss($component['name']) ,
		  $component['type'],
          drupal_render($form['components'][$cid]['translation']) ,
          l(t('Edit'), 'node/' . $node->nid . '/webform/components/translation/'.$cid),
      );
      //localhost/relo/node/1/webform/translation/edit?language=CN

      $row_class = array('draggable');

      $rows[] = array('data' => $row_data, 'class' => $row_class);
      if (isset($component['children']) && is_array($component['children'])) {
        foreach ($component['children'] as $cid => $component) {
          _webform_components_form_rows($node, $cid, $component, $level + 1, $form, $rows, $add_form);
        }
      }

    }//endfunction
    
    
    foreach ($component_tree['children'] as $cid => $component) {
      _webform_components_form_rows($node, $cid, $component, 0, $form, $rows, $add_form);
    }
  }
  else {
    $rows[] = array(array('data' => t('No Components, add a component below.'), 'colspan' => 9));
  }
  

  // Append the add form if not already printed.
  if ($add_form) {
    $rows[] = $add_form;
  }

  $output = '';
  $output .= drupal_render($form['components']['translation_select']);
  $output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'webform-components')));
  $output .= drupal_render_children($form);
  
  return $output;
}

/**
 * Form submit for: 'webform_translation_form'
 */
function webform_translation_form_submit($form, &$form_state) {
  $node = node_load($form_state['values']['nid']);
  $translation_select = $form_state['values']['components']['translation_select'];//The value must > 0
  
  if($translation_select){
    $result = db_query('SELECT lid FROM {webform_translation} WHERE lcode=:lcode', array(':lcode'=>$translation_select));
    $lid = $result->fetch()->lid;
  }else{
    die('error argument.');
  }
  
  foreach ($node->webform['components'] as $cid => $component) {
      $component['nid'] = $node->nid;
      $component['translation'] = $form_state['values']['components'][$cid]['translation'];

      _webform_component_translation_update($component['nid'],$cid,$lid,$component['translation']);
  }
  
  drupal_set_message(t('Save Success.'));
  
  /* if($translation_select){
    $redirect = request_path().'?language='.$translation_select ;
    $form_state['redirect'] = $redirect;
    //drupal_goto($redirect);
  } */
  
  return;
}

//-------------------------------------------------------------------------------------
// Form to configure a webform component's translation.
function webform_component_translation_edit_form($form, $form_state, $node, $component, $clone = FALSE) {
  drupal_set_title(t('Edit component: @name', array('@name' => $component['name'])), PASS_THROUGH);
  
  // Set default translate language in session
  if (!isset($_SESSION['language'])) {
    $_SESSION['language'] = array('lid'=>2, 'lcode'=>'de', 'name'=>'German');
  }
  //print_r($_SESSION);exit;
  //print_r($node);exit;
  //print_r($component);exit;
  $lid = $_SESSION['language']['lid'];
  $translation = _get_webform_component_translation($node->nid, $lid, $component['cid']);	//print_r($translation);exit;
  
  $form['#attached']['library'][] = array('webform', 'admin');
  $form['#tree'] = TRUE;

  // Print the correct field type specification.
  $form['type'] = array(
    '#type' => 'value',
    '#value' => $component['type'],
  );
  $form['nid'] = array(
    '#type' => 'value',
    '#value' => $node->nid,
  );
  $form['cid'] = array(
    '#type' => 'value',
    '#value' => isset($component['cid']) ? $component['cid'] : NULL,
  );
  
  $form['language'] = array(
    '#type' => 'markup',
	'#markup' => "<b>".t('Language').": </b>".$_SESSION['language']['name']."<br><br>",
	'#weight' => -12,
  );
  $form['type_name'] = array(
    '#type' => 'markup',
	'#markup' => "<b>".t('Component').": </b>".$component['type']."<br><br>",
	'#weight' => -11,
  );
  $form['form_key'] = array(
    '#type' => 'markup',
	'#markup' => "<b>".t('Form Key').": </b>".$component['form_key']."<br><br>",
    '#weight' => -10,
  );
  
  if (webform_component_feature($component['type'], 'title')) {
    $form['name'] = array(
      '#type' => 'textfield',
      '#default_value' => $component['name'],
      '#title' => t('Label'),
      '#description' => t('This is used as a descriptive label when displaying this form element.'),
      //'#required' => TRUE,
      '#weight' => -9,
      '#maxlength' => 255*2,
	  '#attributes' => array('readonly' => 'readonly'),
    );
	$form['name_translation'] = array(
      '#type' => 'textfield',
      '#default_value' => isset($translation['name']) ? $translation['name'] : '',
      '#title' => t('Label Translation')."(".$_SESSION['language']['name'].")",
      '#required' => TRUE,
      '#weight' => -8,
      '#maxlength' => 255*2,
    );
  }
  
  if ($component['type'] == 'select') {
    if (isset($component['extra']['items'])) {
	// Load items	dynamic
	//$options     = _webform_select_options($component, !$component['extra']['aslist'], FALSE); 
	//$items_value = _webform_select_options_to_text($options);
        $items_value = $component['extra']['items']; // here only display origal language: english
	  
	$form['items'] = array(
        '#type' => 'textarea',
        '#title' => t('Options'),
        //'#default_value' => $component['extra']['items'],
	'#default_value' => $items_value,
        '#description' => t('<strong>Key-value pairs MUST be specified as "safe_key|Some readable option"</strong>. Use of only alphanumeric characters and underscores is recommended in keys. One option per line. Option groups may be specified with &lt;Group Name&gt;. &lt;&gt; can be used to insert items at the root of the menu after specifying a group.'),
        '#cols' => 60,
        '#rows' => 5,
        '#weight' => -7,
        '#wysiwyg' => FALSE,
        //'#element_validate' => array('_webform_edit_validate_select'),
	'#attributes' => array('readonly' => 'readonly'),
        );
	$form['items_translation'] = array(
        '#type' => 'textarea',
        '#title' => t('Options')."(".$_SESSION['language']['name'].")",
        '#default_value' => isset($translation['items']) ? $translation['items'] : $items_value,
        '#cols' => 60,
        '#rows' => 5,
        '#weight' => -6,
	//'#required' => TRUE,
        '#wysiwyg' => FALSE,
        '#element_validate' => array('_webform_edit_validate_select'),	//Ensure keys are not duplicated
        );
    }
  }
  
  // Markup with 'value' translation, others with 'description' translation
  if ($component['type'] == 'markup') {
	$form['value'] = array(
      '#type' => 'textarea',
      '#title' => t('Values'),
      '#description' => t(''),
      '#default_value' => $component['value'],
	  '#attributes' => array('readonly' => 'readonly'),
	  '#weight' => -7,
    );
	$form['value_translation'] = array(
      '#type' => 'textarea',
      '#title' => t('Values Translation')."(".$_SESSION['language']['name'].")",
      '#default_value' => isset($translation['value']) ? $translation['value'] : '',
	  //'#required' => TRUE,
	  '#weight' => -6,
    );
  }
  else {
  	if (isset($component['extra']['description'])) {
	  $form['description'] = array(
        '#type' => 'textarea',
        '#default_value' => isset($component['extra']['description']) ? $component['extra']['description'] : '',
        '#title' => t('Description'),
        '#description' => t('A short description of the field used as help for the user when he/she uses the form.'),
		'#attributes' => array('readonly' => 'readonly'),
        '#weight' => -5,
      );
	  $form['description_translation'] = array(
        '#type' => 'textarea',
        '#default_value' => isset($translation['description']) ? $translation['description'] : '',
		//'#required' => TRUE,
        '#title' => t('Description Translation')."(".$_SESSION['language']['name'].")",
        '#weight' => -4,
      );
	}
  }
  
  // Add the submit button.
  $form['submit']['save'] = array(
    '#type' => 'submit',
    '#value' => t('Save Translation'),
    '#weight' => 50,
  );
  $form['submit']['cancel'] = array(
    '#type' => 'submit',
    '#value' => t('Cancel'),
    '#attributes' => array(
        //'onclick' => "window.location.href='node/1/webform/translation';" 
    ),
    '#weight' => 51 
  );

  //print_r($form);exit;
  return $form;
}

/**
 * Validation handler for webform_component_translation_edit_form().
 */
function webform_component_translation_edit_form_validate($form, &$form_state) {
  $node = node_load($form_state['values']['nid']);

  //print_r($form_state['values']);exit;
}

/**
 * Submit handler for webform_component_translation_edit_form().
 */
function webform_component_translation_edit_form_submit($form, &$form_state) {
  // Ensure a webform record exists.
  $node = node_load($form_state['values']['nid']);
  webform_ensure_record($node);
  
  if ($form_state['values']['op'] == t('Cancel')) {
    drupal_goto('node/'.$node->nid.'/webform/translation');
  }
  
  // Set default translate language in session
  if (!isset($_SESSION['language'])) {
    $_SESSION['language'] = array('lid'=>2, 'lcode'=>'de', 'name'=>'German');
  }

  //print_r($form_state['values']);exit;
  $cid = $form_state['values']['cid'];
  $lid = $_SESSION['language']['lid'];
  $name        = $form_state['values']['name_translation'];
  $description = isset($form_state['values']['description_translation']) ? $form_state['values']['description_translation'] : 'NOTSET';
  $value       = isset($form_state['values']['value_translation']) ? $form_state['values']['value_translation'] : 'NOTSET';
  $items       = isset($form_state['values']['items_translation']) ? $form_state['values']['items_translation'] : 'NOTSET';
  if (!empty($cid)) {
    _webform_component_translation_update($node->nid, $cid, $lid, $name, trim($description), trim($value), trim($items));
    drupal_set_message(t('Component %name updated.', array('%name' => $form_state['values']['name'])));
  }

  $form_state['redirect'] = array('node/'.$node->nid.'/webform/components/translation/'.$cid, array());
}

/*
 * Update the 'webform_component_translation' data
 */
function _webform_component_translation_update($nid, $cid, $lid, $name='', $description='NOTSET', $value='NOTSET', $items='NOTSET') {
  $table = 'webform_component_translation';
  
  $fields         = array();
  $fields['nid']  = $nid;
  $fields['cid']  = $cid;
  $fields['lid']  = $lid;
  $fields['name'] = $name;
  $update_arr     = array('name'=>$fields['name']);
  $update_str     = " name='".$fields['name']."'";
  if ($description != 'NOTSET') {
    $fields['description'] = $description;
	$update_arr += array('description' => $fields['description']);
	$update_str .= ",description='".$fields['description']."'";
  }
  if ($value != 'NOTSET') {
    $fields['value'] = $value;
	$update_arr += array('value' => $fields['value']);
	$update_str .= ",value='".$fields['value']."'";
  }
  if ($items != 'NOTSET') {
    $fields['items'] = $items;
	$update_arr += array('items' => $fields['items']);
	$update_str .= ",items='".$fields['items']."'";
  }
  
  // Check record exists
  $select_val = array();
  $rs = db_query('SELECT nid FROM {webform_component_translation} WHERE nid = :nid AND cid = :cid AND lid = :lid', array(':nid' => $nid,
':cid' => $cid ,':lid' => $lid));
  foreach($rs as $o){
    $select_val['nid'] =  $o->nid;
  }
  
  if(isset($select_val['nid'])){
    $query = db_update($table)->fields($update_arr)
    ->condition('nid', $nid)
    ->condition('cid', $cid)
    ->condition('lid', $lid)
    ->execute();
	//$sql = "UPDATE {webform_component_translation} set $update_str where nid=$nid and cid=$cid and lid=$lid"; //echo $sql;exit;
	//db_query($sql);
  }
  else {
    $query = db_insert($table)->fields($fields)->execute();
  } 
}
